package com.example.querydsldemo.service.impl;

import com.example.querydsldemo.entity.QUserEntity;
import com.example.querydsldemo.entity.UserEntity;
import com.example.querydsldemo.service.UserService;
import com.example.querydsldemo.service.repository.UserRepository;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    private final JPAQueryFactory jpaQueryFactory;

    private final UserRepository userRepository;

    public UserServiceImpl(JPAQueryFactory jpaQueryFactory, UserRepository userRepository) {
        this.jpaQueryFactory = jpaQueryFactory;
        this.userRepository = userRepository;
    }

    @Override
    public UserEntity save(UserEntity userEntity) {
        return userRepository.saveAndFlush(userEntity);
    }

    @Override
    public UserEntity findByUserName(String userName) {
        QUserEntity qUserEntity = QUserEntity.userEntity;
        return jpaQueryFactory.select(qUserEntity).from(qUserEntity).where(qUserEntity.userName.eq(userName)).fetchFirst();
    }

    @Override
    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }
}
